const {
	Service
} = require('uni-cloud-router')

const dbcmd = uniCloud.database().command;
const $ = dbcmd.aggregate;

module.exports = class CouponService extends Service {

	constructor(ctx) {
		super(ctx)
	}
	
	// 注册用户赠送优惠券
	async registerReward(uid, uname, uheadimg) {
		// 获取可赠送优惠券
		const couponRules = await this.__get_reward_coupon_rules();
		
		if (!(couponRules && couponRules.length)) {
			return;
		}
		
		const coupon_rule_ids = [];
		const coupon_ids = [];
		for (var i = 0; i < couponRules.length; i++) {
			const rule = couponRules[i];
			
			// 获取可待领取的一张优惠券
			const couponRes = await this.db.collection('usemall-marketing-coupon')
				.where({
					is_delete: 0,
					state: '待领取',
					coupon_id: rule._id
				})
				.orderBy('sort', 'desc')
				.limit(1)
				.get();
			
			const [coupon] = couponRes.data;
			if (!(coupon && coupon._id)) {
				continue;
			}
			
			coupon_rule_ids.push(rule._id);
			coupon_ids.push(coupon._id);
		}
		
		// 无可领取优惠券
		if (!coupon_ids.length) return;
		
		// 批量领取优惠券
		// 优惠券数
		await this.db.collection('usemall-member').doc(uid).update({
			member_coupon_cnt: this.db.command.inc(coupon_ids.length)
		});
		// 领取数
		await this.db.collection('usemall-marketing-coupon-rule').where({
			_id: this.db.command.in(coupon_rule_ids)
		}).update({
			receive_num: this.db.command.inc(1)
		});
		// 已领取
		await this.db.collection('usemall-marketing-coupon').where({
			_id: this.db.command.in(coupon_ids)
		}).update({
			version: this.db.command.inc(1),
			state: '已领取',
			
			member_id: uid,
			member_name: uname,
			member_headimg: uheadimg,
			note: '注册赠送专属优惠券',
			
			last_modify_time: Date.now(),
			last_modify_uid: uid,
			last_modify_uname: uname
		});
	}
	
	// 获取可赠送优惠券
	async __get_reward_coupon_rules() {
		const nowdate = Date.now();
		const ruleRes = await this.db.collection('usemall-marketing-coupon-rule')
			.where( 
				this.db.command.and([
					{
						is_delete: 0,
						state: '运营中',
						receive_type: '注册会员',
						member_type: '所有人',
						start_time: $.lte(nowdate),
						end_time: $.gt(nowdate) 
					}, 
					this.db.command.expr($.gt(['$num', '$receive_num']))
				])
			)
			.get();
		
		return ruleRes.data;
	}
	
}
